#! /usr/bin/env python
# -*- coding: utf-8 -*-
#authored by yangsen、lpc

import matplotlib.pyplot as plt
import numpy as np
from PIL import Image


def parse_curve(order):
    img = Image.open('static/images/progress.png')

    data = img.load()
    imgSize = img.size

    width = img.width
    height = img.height

    xList = []
    yList = []

    for x in range(0, width - 1):
        for y in range(0, height - 1):
            item = data[x, y]
            nums = []
            if item[3] > 0:
                nums.append(-y)

            if len(nums) > 0:
                xList.append(x)
                yList.append(sum(nums) / len(nums))

    # print(xList)
    # print(yList)

    f1 = np.polyfit(xList, yList, int(order))

    # print("f1 is :\n", f1)
    lua_express = ""
    for i in range(len(f1)):

        nomial = "(%s * x^(%s)) + " % (f1[i], int(order) - i)
        if int(order) - i == 0:
            nomial = "%s" % (f1[i])
        # print(nomial)
        lua_express += nomial

    # print(lua_express)

    p1 = np.poly1d(f1)
    # print("p1 is :\n", p1)

    # 也可使用yvals=np.polyval(f1, x)
    yvals = p1(xList)
    # print('yvals is :\n', yvals)
    # 绘图
    plt.clf()
    plt.plot(xList, yList, 's', label='original values')
    plt.plot(xList, yvals, 'r', label='polyfit values')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.legend(loc=4)  # 指定legend的位置右下角
    plt.title('polyfitting')
    plt.savefig("static/images/curve.png")
    # plt.show()

    return p1, lua_express
